<?php
namespace App\Http\Model;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Popularize extends Base
{
    protected $table_name = "user_referrer";
    private $redis_cache_seconds = 30 * 60;
    private $cache_popularize_bind = "CACHE:POPULARIZE:";
    
    public function __construct()
    {
        parent::__construct($this->table_name);
    }
    
    /**
     * 创建用户与推荐人关系
     * @param int $uid  用户id
     * @param int $bid  推荐人id
     * @return int
     */
    public function create_relation(int $uid, int $bid)
    {
        return DB::insert("INSERT IGNORE INTO zb_{$this->table} (uid,bid) VALUES(?,?)",[$uid,$bid]);
    }
    
    /**
     * 缓存推荐码与客户的联系
     * @param string $key
     * @param string $code
     * @return mixed
     */
    public function set_recommend_code(string $key,string $code)
    {
        $ip = get_remote_addr();
        return Redis::SET($this->cache_popularize_bind.$key."#{$ip}",$code,'NX','EX', $this->redis_cache_seconds);
    }
    
    /**
     * 获取推荐码
     * @param string $key
     * @return mixed
     */
    public function get_recommend_code(string $key)
    {
        $ip = get_remote_addr();
        $code = Redis::GET($this->cache_popularize_bind.$key."#".$ip);
        return $code;
    }
    
    /**
     * 删除绑定码
     * @param string $key
     * @return mixed
     */
    public function remove_recommend_code(string $key){
        $ip = get_remote_addr();
        return Redis::DEL($this->cache_popularize_bind.$key."#".$ip);
    }
    
}